package com.engine.cn.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.engine.cn.service.InventoryService;


import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class InventoryServiceImpl implements InventoryService {
    private final Lock lock = new ReentrantLock();

    @Value("${server.port}")
    private String port;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 需要保证死锁，锁需要加过期时间，不能一直占用，只能自己删除自己的锁，不能删除别人的锁
     *
     * @return String
     * @throws InterruptedException 异常
     */
    @Override
    public String sale() throws InterruptedException {
        String message;
        String key = "inventoryLock";
        String value = UUID.randomUUID().toString() + Thread.currentThread().getId();
        //自旋获取锁，30秒自动过期，枷锁和过期时间必须写到一行，保证原子性
        while (!redisTemplate.opsForValue().setIfAbsent(key, value, 30L, TimeUnit.SECONDS)) {
            //暂停20秒重试
            TimeUnit.MICROSECONDS.sleep(20);
        }

        try {
            //查询订单消息
            String result = redisTemplate.opsForValue().get("inventory001");
            //判断库存是否足够
            int inventoryNumber = Objects.isNull(result) ? 0 : Integer.parseInt(result);
            //减库存
            if (inventoryNumber > 0) {
                redisTemplate.opsForValue().set("inventory001", String.valueOf(--inventoryNumber));
                message = "成功卖出一个商品，剩余库存量" + (--inventoryNumber) + "端口号是：" + port;
                System.out.println(message);
            } else {
                message = "商品卖完了";
            }
        } finally {
            //只允许删除自己的锁，不允许删除别人的锁
            if (value.equals(redisTemplate.opsForValue().get(key))) {
                redisTemplate.delete(key);
            }
        }

        return message;
    }

    /**
     * 废弃版本，
     *
     * @return String
     */
    public String discardSale() {
        String message;
        lock.lock();
        try {
            //查询订单消息
            String result = redisTemplate.opsForValue().get("inventory001");
            //判断库存是否足够
            int inventoryNumber = Objects.isNull(result) ? 0 : Integer.parseInt(result);
            //减库存
            if (inventoryNumber > 0) {
                redisTemplate.opsForValue().set("inventory001", String.valueOf(--inventoryNumber));
                message = "成功卖出一个商品，剩余库存量" + (--inventoryNumber) + "端口号是：" + port;
                System.out.println(message);
            } else {
                message = "商品卖完了";
            }
        } finally {
            lock.unlock();
        }

        return message;
    }
}
